package com.centaline.androidsalesblog.activities.mine;

import android.content.Intent;
import android.support.v7.widget.AppCompatCheckBox;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.activities.newest.NewEstActDetailActivity;
import com.centaline.androidsalesblog.activities.newest.NewEstDetailActivity;
import com.centaline.androidsalesblog.activities.sale.EsfEstateDetailActivity;
import com.centaline.androidsalesblog.activities.sale.RentDetailActivity;
import com.centaline.androidsalesblog.activities.sale.SaleDetailActivity;
import com.centaline.androidsalesblog.adapter.FootPrintAdapter;
import com.centaline.androidsalesblog.base.BaseActivity;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.iml.RecyclerViewItemOnClickListener;
import com.centaline.androidsalesblog.model.businissobject.HistoryBo;
import com.centaline.androidsalesblog.model.businissobject.HistoryInDateBo;
import com.centaline.androidsalesblog.model.databaseobject.BizUnitDo;
import com.centaline.androidsalesblog.rx.database.RxDataBase;
import com.centaline.androidsalesblog.utils.DateUtil;
import com.centanet.framework.glide.GlideLoad;
import com.trello.rxlifecycle.ActivityEvent;

import java.util.ArrayList;
import java.util.Locale;

import ca.barrenechea.widget.recyclerview.decoration.StickyHeaderDecoration;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func2;
import rx.schedulers.Schedulers;

/**
 * 足迹
 * <p/>
 * Created by fusl1 on 2015/12/24.
 */
public class FootPrintActivity extends BaseActivity implements View.OnClickListener {

    private ImageView img_left, img_right;
    private AppCompatTextView atv_month, atv_year, atv_no_date;
    private RecyclerView recyclerView;

    private RelativeLayout rl_delete_tool;
    private AppCompatCheckBox cb_all;
    private Button btn_delete;

    private FootPrintAdapter footPrintAdapter;
    private ArrayList<HistoryInDateBo> list = new ArrayList<>();
    private int selectPos;
    private int mode;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_foot_print;
    }

    @Override
    protected void findViews() {
        setUniversalToolbar(R.string.title_foot_print);
        img_left = (ImageView) findViewById(R.id.img_left);
        img_right = (ImageView) findViewById(R.id.img_right);
        atv_month = (AppCompatTextView) findViewById(R.id.atv_month);
        atv_year = (AppCompatTextView) findViewById(R.id.atv_year);
        atv_no_date = (AppCompatTextView) findViewById(R.id.atv_no_date);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        rl_delete_tool = (RelativeLayout) findViewById(R.id.rl_delete_tool);
        cb_all = (AppCompatCheckBox) findViewById(R.id.cb_all);
        btn_delete = (Button) findViewById(R.id.btn_delete);
    }

    @Override
    protected void initViews() {
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        cb_all.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                footPrintAdapter.selectAll(isChecked);
                btn_delete.setEnabled(isChecked);
            }
        });

        footPrintAdapter = new FootPrintAdapter(this, GlideLoad.init(this));
        footPrintAdapter.setItemOnClickListener(new RecyclerViewItemOnClickListener<HistoryBo>() {
            @Override
            public void onItemOnClick(HistoryBo historyBo, int tag) {
                if (tag == 1)
                    return;
                switch (historyBo.getType()) {
                    case 0:
                        startActivity(new Intent(FootPrintActivity.this, SaleDetailActivity.class)
                                .putExtra(ExtraConstant.PostId, historyBo.getPostDo().getPostId()));
                        break;
                    case 1:
                        startActivity(new Intent(FootPrintActivity.this, RentDetailActivity.class)
                                .putExtra(ExtraConstant.PostId, historyBo.getPostDo().getPostId()));
                        break;
                    case 2:
                        startActivity(new Intent(FootPrintActivity.this, EsfEstateDetailActivity.class)
                                .putExtra(ExtraConstant.CestCode, historyBo.getEsfEstateDo().getCestCode()));
                        break;
                    case 3:
                        startActivity(new Intent(FootPrintActivity.this, NewEstDetailActivity.class)
                                .putExtra(ExtraConstant.NewEstId, historyBo.getNewEstDo().getEstExtId()));
                        break;
                    case 4:
                        startActivity(new Intent(FootPrintActivity.this, NewEstActDetailActivity.class)
                                .putExtra(ExtraConstant.NewEstActId, historyBo.getNewEstActDo().getActId()));
                        break;
                    default:
                        break;
                }
            }
        });
        footPrintAdapter.setListChangeListener(new FootPrintAdapter.ListChangeListener() {
            @Override
            public void change(boolean selectAll, boolean hasSelect) {
                cb_all.setChecked(selectAll);
                btn_delete.setEnabled(hasSelect);
            }
        });
        recyclerView.addItemDecoration(new StickyHeaderDecoration(footPrintAdapter));
        recyclerView.setAdapter(footPrintAdapter);

        Observable.combineLatest(RxDataBase.getFpHistory(),
                RxDataBase.getBizUnit(),
                new Func2<ArrayList<HistoryInDateBo>, BizUnitDo, ArrayList<HistoryInDateBo>>() {
                    @Override
                    public ArrayList<HistoryInDateBo> call(ArrayList<HistoryInDateBo> historyInDateBos, BizUnitDo bizUnitDo) {
                        footPrintAdapter.setNewPropImg(bizUnitDo.getNewpropimg());
                        return historyInDateBos;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<ArrayList<HistoryInDateBo>>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<ArrayList<HistoryInDateBo>>() {
                    @Override
                    public void call(ArrayList<HistoryInDateBo> historyInDateBos) {
                        if (historyInDateBos != null) {
                            list.addAll(historyInDateBos);
                        }
                        select(0);
                        invalidateOptionsMenu();
                    }
                });
    }

    /**
     * 选择
     */
    private void select(int position) {
        selectPos = position;
        if (list.size() == 0) {
            final String date = DateUtil.format(System.currentTimeMillis(), DateUtil.FORMAT6);
            if (date.contains("-")) {
                final String[] dates = date.split("-");
                atv_month.setText(String.format(Locale.CHINA, "%s月", dates[1]));
                atv_year.setText(dates[0]);
            } else {
                atv_month.setText(date);
            }
            footPrintAdapter.recyclerList(new ArrayList<HistoryBo>());
            setLeftVisible(false);
            setRightVisible(false);
            atv_no_date.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
        } else {
            final HistoryInDateBo historyInDateBo = list.get(position);
            final String date = DateUtil.format(historyInDateBo.getDate(), DateUtil.FORMAT6);
            if (date.contains("-")) {
                final String[] dates = date.split("-");
                atv_month.setText(String.format(Locale.CHINA, "%s月", dates[1]));
                atv_year.setText(dates[0]);
            } else {
                atv_month.setText(date);
            }
            footPrintAdapter.recyclerList(historyInDateBo.getList());
            setLeftVisible(list.size() - selectPos > 1);
            setRightVisible(selectPos > 0);
        }
    }

    /**
     * 删除操作
     */
    private void delete() {
        mode = 0;
        footPrintAdapter.setMode(mode, false);
        final ArrayList<HistoryBo> temp = footPrintAdapter.getSelectArrayList();
        if (temp.size() > 0) {
            RxDataBase
                    .deleteFpHistory(temp)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .compose(this.<Boolean>bindUntilEvent(ActivityEvent.DESTROY))
                    .subscribe(new Action1<Boolean>() {
                        @Override
                        public void call(Boolean aBoolean) {
                            if (temp.size() == list.get(selectPos).getList().size()) {//全部删除操作
                                list.remove(selectPos);
                                select(selectPos == 0 ? selectPos : selectPos--);
                            } else {
                                for (HistoryBo historyBo : temp) {
                                    list.get(selectPos).getList().remove(historyBo);
                                }
                                select(selectPos);
                            }
                            cb_all.setChecked(false);
                            btn_delete.setEnabled(false);
                            rl_delete_tool.setVisibility(View.GONE);
                            invalidateOptionsMenu();
                        }
                    });
        }
    }

    private void setLeftVisible(boolean visible) {
        img_left.setEnabled(visible);
        img_left.setVisibility(visible ? View.VISIBLE : View.INVISIBLE);
    }

    private void setRightVisible(boolean visible) {
        img_right.setEnabled(visible);
        img_right.setVisibility(visible ? View.VISIBLE : View.INVISIBLE);
    }

    /**
     * 更新UI
     */
    private void updateUi() {
        footPrintAdapter.setMode(mode);
        rl_delete_tool.setVisibility(mode == 1 ? View.VISIBLE : View.GONE);
        setLeftVisible(mode == 0 && list.size() - selectPos > 1);
        setRightVisible(mode == 0 && selectPos > 0);
        invalidateOptionsMenu();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_left:
                if (selectPos < list.size() - 1) {
                    select(selectPos + 1);
                }
                break;
            case R.id.img_right:
                if (selectPos > 0)
                    select(selectPos - 1);
                break;
            case R.id.btn_delete:
                delete();
                break;
            default:
                break;
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_delete, menu);
        MenuItem delete = menu.findItem(R.id.action_delete);
        MenuItem complete = menu.findItem(R.id.action_complete);
        delete.setVisible(mode == 0 && footPrintAdapter.getList().size() > 0);
        complete.setVisible(mode == 1);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_delete) {
            mode = 1;
            updateUi();
            return true;
        } else if (item.getItemId() == R.id.action_complete) {
            mode = 0;
            updateUi();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
